package search;

import LinkedList.Leetcode21_MergeLinkedList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @author Hongliang Zhu
 * @create 2020-09-18 15:42
 *
 * 全排列II
 * 给定一个可包含重复数字的序列，返回所有不重复的全排列。
 *
 * 示例:
 *
 * 输入: [1,1,2]
 * 输出:
 * [
 *   [1,1,2],
 *   [1,2,1],
 *   [2,1,1]
 * ]
 *
 */
public class leetcode_47permuteUnique {
    List<List<Integer>>  res = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {

        Arrays.sort(nums);
        boolean[] vis = new boolean[nums.length];
        backtrack(nums, 0 , new ArrayList<>(), vis);
        return res;
    }

    private void backtrack(int[] nums, int pos, ArrayList<Integer> ans, boolean[] vis) {
        if(ans.size() == nums.length){
            res.add(new ArrayList<>(ans));
            return;
        }
        for(int i = 0; i < nums.length; i++){
//            if(i != pos && nums[i]!= nums[i+1])
            if(vis[i] || (i > 0 && nums[i] == nums[i-1] && vis[i-1] == false)){
                continue;
            }
            ans.add(nums[i]);
            vis[i] = true;
            backtrack(nums, i+1, ans, vis);
            vis[i] = false;
            ans.remove(ans.size()-1);
        }
    }

    public static void main(String[] args) {
        leetcode_47permuteUnique solution = new leetcode_47permuteUnique();
        int[] nums = {1,1,1};
        List<List<Integer>> lists = solution.permuteUnique(nums);
        System.out.println(lists);
    }
}
